import os
import ssl
from flask import Flask
from flask_mail import Mail, Message
from dotenv import load_dotenv
import smtplib

from email_content import (feedback_reply_html)

# 加载环境变量
load_dotenv()


class EmailSender:
    def __init__(self):
        # 初始化Flask应用
        self.app = Flask(__name__)

        # 配置邮件服务器
        self._setup_mail_config()

        # 初始化邮件扩展
        self.mail = Mail(self.app)

        # 记录最后一次发送结果
        self.last_result = {
            'success': False,
            'message': '',
            'timestamp': None
        }

    def _setup_mail_config(self):
        """配置邮件服务器参数，支持SSL和TLS"""
        # 基础服务器配置
        self.app.config['MAIL_SERVER'] = os.getenv('MAIL_SERVER')
        self.app.config['MAIL_PORT'] = int(os.getenv('MAIL_PORT', 587))

        # 加密方式配置
        self.app.config['MAIL_USE_TLS'] = os.getenv('MAIL_USE_TLS', 'False').lower() == 'true'
        self.app.config['MAIL_USE_SSL'] = os.getenv('MAIL_USE_SSL', 'False').lower() == 'true'

        # 认证信息
        self.app.config['MAIL_USERNAME'] = os.getenv('MAIL_USERNAME')
        self.app.config['MAIL_PASSWORD'] = os.getenv('MAIL_PASSWORD')
        self.app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_DEFAULT_SENDER',
                                                           os.getenv('MAIL_USERNAME'))

        # 增强配置
        self.app.config['MAIL_TIMEOUT'] = 15  # 超时时间
        self.app.config['MAIL_DEBUG'] = os.getenv('MAIL_DEBUG', 'False').lower() == 'true'  # 调试模式

        # SSL上下文配置（针对SSL连接）
        if self.app.config['MAIL_USE_SSL']:
            self.app.config['MAIL_SSL_CONTEXT'] = ssl.create_default_context()

    def send_email(self, to, subject, body, html=None, cc=None, bcc=None):
        """
        发送邮件（增强版）
        :param to: 收件人邮箱（字符串或列表）
        :param subject: 邮件主题
        :param body: 文本正文
        :param html: HTML正文（可选）
        :param cc: 抄送（可选）
        :param bcc: 密送（可选）
        :return: 成功返回True，失败返回False
        """
        # 验证必要参数
        if not to or not subject or not body:
            error_msg = "收件人、主题和正文为必填项"
            self.last_result = {'success': False, 'message': error_msg, 'timestamp': self._get_timestamp()}
            print(f"邮件发送失败: {error_msg}")
            return False

        try:
            with self.app.app_context():
                # 处理收件人格式
                recipients = [to] if isinstance(to, str) else to

                # 处理抄送和密送
                cc_list = [cc] if cc and isinstance(cc, str) else (cc if isinstance(cc, list) else None)
                bcc_list = [bcc] if bcc and isinstance(bcc, str) else (bcc if isinstance(bcc, list) else None)

                # 创建邮件消息
                msg = Message(
                    subject=subject,
                    recipients=recipients,
                    body=body,
                    html=html,
                    cc=cc_list,
                    bcc=bcc_list
                )

                # 发送邮件
                self.mail.send(msg)

                # 更新发送结果
                success_msg = f"邮件成功发送至: {', '.join(recipients)}"
                self.last_result = {
                    'success': True,
                    'message': success_msg,
                    'timestamp': self._get_timestamp()
                }
                print(success_msg)
                return True

        except smtplib.SMTPAuthenticationError:
            error_msg = "认证失败：用户名或授权码错误"
        except smtplib.SMTPConnectError:
            error_msg = f"连接失败：无法连接到 {self.app.config['MAIL_SERVER']}:{self.app.config['MAIL_PORT']}"
        except smtplib.SMTPTimeoutError:
            error_msg = "连接超时：服务器未在规定时间内响应"
        except Exception as e:
            error_msg = f"发送失败：{str(e)}"

        # 记录失败信息
        self.last_result = {'success': False, 'message': error_msg, 'timestamp': self._get_timestamp()}
        print(f"邮件发送失败: {error_msg}")
        return False

    def get_last_result(self):
        """获取最后一次发送结果"""
        return self.last_result.copy()

    def _get_timestamp(self):
        """获取当前时间戳"""
        from datetime import datetime
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


# 单例实例
email_sender = EmailSender()

# 测试代码（直接运行时执行）
if __name__ == "__main__":
    # 替换为实际收件人邮箱
    test_recipient = "3193323975@qq.com"
    test_name='lsl'
    feedback_topic='nihao'

    html = feedback_reply_html.format(name=test_name,
                                      feedback_topic=feedback_topic,
                                      your_email=test_recipient)



    # 发送测试邮件
    success = email_sender.send_email(
        to=test_recipient,
        subject="邮件发送测试",
        body="这是一封通过优化后的邮件发送工具发送的测试邮件1919919191。",
        html=html
    )

    # 输出结果
    print("\n测试结果:", "成功" if success else "失败")
    print("详细信息:", email_sender.get_last_result())
